<?php

class Truck_appointmentController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='create';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter'),
			array('application.filters.AuthFilter'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow(){	
		
		$model=$this->loadTruck_appointment();
		$goods_models=$this->loadGoods_info();
		$deadhead_models=$this->loadDeadhead_info();
		$this->render('show',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_models'=>$deadhead_models));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{	
		$model=new Truck_appointment;
		$model->business_time=date('Y-m-d');//业务时间默认当日
		$g_model=new Goods_info;
		$s_model;
		$create_ok=0;
		if(isset($_GET['sid'])){//由计划单导入
			$s_model=$this->scheduleToGoods($_GET['sid'],$g_model);
			$model->total_amount=$s_model->freight_charge;
			$create_ok=2;
			unset($_GET['sid']);
		}
		
		$goods_models=array($g_model);
		$deadhead_temp=new Deadhead_info;//提货空驶模板
		$deadhead_models=array();//建立空数组 可能不存在提货空驶信息
		if(isset($_POST['Truck_appointment']))
		{
			$deadheads=array();
			$goods=array();
			
			$model->attributes=$_POST['Truck_appointment'];
			if(isset($_POST['goods']))//判断是否存在货物信息
				$goods=$_POST['goods'];
			else
				$goods_models=array();
				
			if(isset($_POST['deadhead']))//判断是否存在提货空驶信息
				$deadheads=$_POST['deadhead'];
				
			$create=true;
			foreach($goods as $n=>$val){
				$goods_model=new Goods_info;
				$goods_model->attributes=$val;
				$goods_models[$n]=$goods_model;
				$create=$goods_model->validate()==true?$create:false;
			}
			foreach($deadheads as $n=>$val){
				$deadhead_model=new Deadhead_info;
				$deadhead_model->attributes=$val;
				$deadhead_models[$n]=$deadhead_model;
				$create=$deadhead_model->validate()==true?$create:false;
			}
			
			if($model->loading_status==0){
				$model->setScenario('heaven');
				$model->origin=$goods_models[0]->origin;
				$model->destination=$goods_models[0]->destination;
			}
			else
				$model->setScenario('empty');
			$create=$model->validate()==true?$create:false;//验证事故信息
			if($create){//全部验证通过  添加数据库 启动事务
				$tran=$model->getDbConnection()->beginTransaction();
				
				$sh_lock_time_id=shmop_open(2, "w", 0, 0);
				$lock_time=shmop_read($sh_lock_time_id, 0, 10);
				$shid=shmop_open(1, "w", 0, 0);
				try{
					while(true){//派车单号锁
						if(shmop_read($shid, 0, 1)==0||(mktime()-$lock_time)>30)
							break;
						sleep(1);	
					}
					shmop_write($shid, 1, 0);
					shmop_write($sh_lock_time_id, mktime(), 0);
					$time_no=$bodytag = str_replace('-','',$model->business_time);//将业务时间转换20100816
					$criteria=new CDbCriteria();//查找业务时间指定的最后的派车单
					$criteria->addCondition("business_time='".$model->business_time."'");
					$criteria->order='appointment_no desc';
					$m=Truck_appointment::model()->find($criteria);
					$serial='001';
					if(isset($m)){//业务时间指定的时间存在派车单
						$appointment_no=$m->appointment_no;
						//$no=substr($appointment_no,0,8);
						//if($time_no==$no){
							$old_serial=substr($appointment_no,8);
							$serial=substr(strval(++$old_serial+1000),1,3);
						//}
					}
					$model->appointment_no=$time_no.$serial;
					
					$model->save(false);
					foreach($goods_models as $val){
						$val->fk_appointment_id=$model->id;
						$val->save(false);
					}
					foreach($deadhead_models as $val){
						$val->fk_appointment_id=$model->id;
						$val->save(false);
					}
					if(isset($s_model)){//如果为计划单导入  删除此计划单
						$s_model->state=1;
						$s_model->save(false);
						Yii::app()->runController('site/makeReminderPage');//生成首页静态页面
					}
					$tran->commit();
					shmop_write($shid, 0, 0);
					shmop_close($shid); 
					shmop_close($sh_lock_time_id); 
					
					if($model->send_sms==0){//向司机发送短信
						$sms_model=new Sms_queue;
						$sms_model->receiver_name=$model->driver1_name;
						$sms_model->mobile_no=$model->driver1_mobile;
						if($model->loading_status==0){
							$msg=',请将货物'.$goods_models[0]->goods_name.'从'.$goods_models[0]->origin.
							'运往'.$goods_models[0]->destination.',数量'.
							$goods_models[0]->amount.$goods_models[0]->getUnitName().'。派车单:'.$model->appointment_no.'。';
						}
						else{
							$msg=',请将车从'.$model->origin.'空驶至'.$model->destination.'。派车单:'.$model->appointment_no.'。';
						}
						$sms_model->msg=$model->driver1_name.$msg;
						$sms_model->save();
						if(isset($model->driver2_name)&&$model->driver2_name!=''){
							$sms1_model=new Sms_queue;
							$sms1_model->receiver_name=$model->driver2_name;
							$sms1_model->mobile_no=$model->driver2_mobile;
							$sms1_model->msg=$model->driver2_name.$msg;
							$sms1_model->save();
						}
					}
				}
				catch(Exception $e){
					shmop_write($shid, 0, 0);
					shmop_close($shid);
					shmop_close($sh_lock_time_id); 
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_models'=>$deadhead_models,'ret'=>'create','info'=>'添加成功！派车单号:'.$model->appointment_no));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'create','ok'=>$create_ok));
			}
		}
		$this->render('create',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_temp'=>$deadhead_temp,'deadhead_models'=>$deadhead_models));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadTruck_appointment();
		$goods_models=$this->loadGoods_info();
		$deadhead_models=$this->loadDeadhead_info();
		$deadhead_temp=new Deadhead_info;//提货空驶模板
		
		if(isset($_POST['Truck_appointment'])){//将所有费用赋值 并且验证
			$deadheads=array();
			$goods=array();
			$model->attributes=$_POST['Truck_appointment'];
			
			if(isset($_POST['goods']))//判断是否存在货物信息
				$goods=$_POST['goods'];
				
			if(isset($_POST['deadhead']))//判断是否存在提货空驶信息
				$deadheads=$_POST['deadhead'];
			
			$goods_sum=count($goods);
			$goods_models_sum=count($goods_models);
			$update=true;
			if($goods_sum==$goods_models_sum){//费用信息数量没变
				foreach($goods as $n=>$val){
					$goods_model=$goods_models[$n];
					$goods_model->attributes=$val;
					$update=$goods_model->validate()==true?$update:false;
				}
			}
			else if($goods_sum>$goods_models_sum){//费用信息数量增加
				foreach($goods as $n=>$val){
					$goods_model=isset($goods_models[$n])?$goods_models[$n]:new Goods_info;
					$goods_model->attributes=$val;
					$update=$goods_model->validate()==true?$update:false;
					$goods_models[$n]=$goods_model;
				}
			}
			else if($goods_sum<$goods_models_sum){//费用信息数量减少
				foreach($goods_models as $n=>$val){
					if(isset($goods[$n])){
						$val->attributes=$goods[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			$deadheads_sum=count($deadheads);
			$deadhead_models_sum=count($deadhead_models);
			if($deadheads_sum==$deadhead_models_sum){//费用信息数量没变
				foreach($deadheads as $n=>$val){
					$deadhead_model=$deadhead_models[$n];
					$deadhead_model->attributes=$val;
					$update=$deadhead_model->validate()==true?$update:false;
				}
			}
			else if($deadheads_sum>$deadhead_models_sum){//费用信息数量增加
				foreach($deadheads as $n=>$val){
					$deadhead_model=isset($deadhead_models[$n])?$deadhead_models[$n]:new Deadhead_info;
					$deadhead_model->attributes=$val;
					$update=$deadhead_model->validate()==true?$update:false;
					$deadhead_models[$n]=$deadhead_model;
				}
			}
			else if($deadheads_sum<$deadhead_models_sum){//费用信息数量减少
				foreach($deadhead_models as $n=>$val){
					if(isset($deadheads[$n])){
						$val->attributes=$deadheads[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			if($model->loading_status==0){
				$model->setScenario('heaven');
				$model->origin=$goods_models[0]->origin;
				$model->destination=$goods_models[0]->destination;
			}
			else
				$model->setScenario('empty');
			$update=$model->validate()==true?$update:false;//验证事故信息
			if($update){//全部验证通过  添加数据库
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($goods_models as $n=>$val){
						$val->fk_appointment_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($goods_models[$n]);
					}
					foreach($deadhead_models as $n=>$val){
						$val->fk_appointment_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($deadhead_models[$n]);
					}
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_models'=>$deadhead_models,'ret'=>'admin','info'=>'更新成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'admin','ok'=>'1')+$_GET);
			}
		}
		$this->render('update',array('model'=>$model,'goods_models'=>empty($goods_models)?array(new Goods_info):$goods_models,'deadhead_temp'=>$deadhead_temp,'deadhead_models'=>$deadhead_models));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			$truck_appointment=Truck_appointment::model();
			$goods=Goods_info::model();
			$deadhead=Deadhead_Info::model();
			$tran=$truck_appointment->getDbConnection()->beginTransaction();
			try{
				$truck_appointment->updateByPk($_GET['id'],array('state'=>1));
				$goods->updateAll(array('state'=>1),array('condition'=>'fk_appointment_id='.$_GET['id']));
				$deadhead->updateAll(array('state'=>1),array('condition'=>'fk_appointment_id='.$_GET['id']));
				$tran->commit();
			}
			catch(Exception $e){
				$tran->rollBack();
				throw $e;
			}
			unset($_GET['id']);
			$this->redirect(array('admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{	
		$this->search(false);
	}
	
	public function actionSearch(){
		$this->search();
	}
	
	private function search($method=true){
		$criteria=new CDbCriteria();//LEFT JOIN goods_name ON goods_name.id=goods.fk_goods_name_id
		$criteria->join='INNER JOIN trucks ON trucks.id=truck_appointment.fk_truck_id
						 LEFT JOIN trucks as board ON board.id=truck_appointment.fk_board_id
						 INNER JOIN truck_type_info as tti ON tti.id=truck_appointment.fk_type_id
						 INNER JOIN drivers as driver1 ON driver1.id=truck_appointment.fk_driver1_id
						 LEFT JOIN goods_info as goods ON goods.fk_appointment_id=truck_appointment.id and goods.state=0
						 LEFT JOIN consignor_info as consignor ON consignor.id=goods.fk_consignor_id
						 LEFT JOIN consignee_info as consignee ON consignee.id=goods.fk_consignee_id
						 LEFT JOIN path ON path.id=goods.fk_path_id';
		$criteria->select='trucks.plate_no as truck_plate_no,board.plate_no as board_plate_no,tti.type_name as type,
				driver1.name as driver1_name,consignor.name as consignor_name,consignee.name as consignee_name,
				goods.goods_name as goods_name,goods.demand_deliver_time as goods_demand_deliver_time,truck_appointment.*';
		$criteria->group='truck_appointment.id';
		$criteria->addCondition('truck_appointment.state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key=='s_date'){//时间查询
					$criteria->addCondition("date_format(truck_appointment.business_time,'%Y-%m')='{$val}'");
				}/*
				else if($key=='e_date'){//时间查询  
					$t=date('Y-m-d',strtotime($val." +1days"));
					$criteria->addCondition("goods.demand_deliver_time<'{$t}' or (isnull(goods.id) and truck_appointment.business_time<'{$t}')");
				}*/	
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		
		if(isset($_GET['excel']))
			$this->toExcel($criteria);
		else	
			$this->toAdminPage($criteria,$method);
		
	}
	
	public function toAdminPage($criteria,$method){
		$model=Truck_appointment::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select truck_appointment.id FROM truck_appointment";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		
		$pages->pageSize=Yii::app()->params['page_size']['truck_appointment'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Truck_appointment');
		$sort->defaultOrder='appointment_no desc';
		$sort->attributes=array_merge($model->attributeNames(),array('truck_plate_no','board_plate_no','type',
		'driver1_name','consignor_name','consignee_name','goods_name','goods_demand_deliver_time','origin','destination'));
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'search'=>$method,
		));
	}
	
	public function toExcel($criteria){
		$model=Truck_appointment::model();
		$sort=new CSort('Truck_appointment');
		$sort->defaultOrder='appointment_no desc';
		$sort->attributes=array_merge($model->attributeNames(),array('truck_plate_no','board_plate_no','type',
		'driver1_name','consignor_name','consignee_name','goods_name','goods_demand_deliver_time','origin','destination'));
		$sort->applyOrder($criteria);
		$models=$model->findAll($criteria);

		$atrr_names=$model->attributeLabels();
		$excel_names=$model->excelAttributes();$end_cell=end($excel_names);
		$tab_name='派车单';
		
		require_once './protected/extensions/excel/PHPExcel.php';
		require_once './protected/extensions/excel/PHPExcel/IOFactory.php';
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)->setTitle($tab_name);
		$objPHPExcel->getActiveSheet()->mergeCells('A1:'.$end_cell[0].'1');
		$objPHPExcel->getActiveSheet()->setCellValue('A1',$tab_name);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(15);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal('center');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->setCellValue('A2','序号');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->freezePane('A3');//标题栏 冻结窗口
		foreach($excel_names as $attr=>$val){//创建标题
			$objPHPExcel->getActiveSheet()->setCellValue($val[0].'2',$atrr_names[$attr]);
			$objPHPExcel->getActiveSheet()->getColumnDimension($val[0])->setWidth($val[1]);
		}
		$row_index=3;//行索引 数据从3开始 例如A从A3开始添加数据
		foreach($models as $n=>$model){
			$objPHPExcel->getActiveSheet()->setCellValue('A'.($n+$row_index),$n+1);
			foreach($excel_names as $attr=>$val){//双循环，根据model内设置进行数据导出
				$value=$model->$attr;
				if(isset($val[2]))//值->字符串 转换
					$value=$model->$val[2]();
				$sheet=$objPHPExcel->getActiveSheet()->setCellValue($val[0].($n+$row_index),$value);
				if(isset($val['format']))//数值太大，按照常规数值显示
					$sheet->getStyle($val[0].($n+$row_index))->getNumberFormat()->setFormatCode($val['format']);
			}
		}
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.iconv("utf-8", "gb2312", $tab_name.'.xls'));
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); 
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadTruck_appointment($id=null)
	{
		if($id!==null || isset($_GET['id'])){
				$criteria=new CDbCriteria();
				$criteria->join='INNER JOIN trucks ON trucks.id=truck_appointment.fk_truck_id
								 LEFT JOIN trucks as board ON board.id=truck_appointment.fk_board_id
								 INNER JOIN truck_type_info as tti ON tti.id=truck_appointment.fk_type_id
								 INNER JOIN truck_type_info as tti1 ON tti1.id=trucks.fk_type_id
								 INNER JOIN drivers as driver1 ON driver1.id=truck_appointment.fk_driver1_id
								 LEFT JOIN drivers as driver2 ON driver2.id=truck_appointment.fk_driver2_id
								 INNER JOIN users as create_user ON create_user.id=truck_appointment.fk_create_user_id
								 INNER JOIN users as update_user ON update_user.id=truck_appointment.fk_update_user_id';
				$criteria->select='trucks.plate_no as truck_plate_no,board.plate_no as board_plate_no,tti.type_name as type,
				driver1.name as driver1_name,driver1.mobile_no as driver1_mobile,driver2.name as driver2_name,
				driver2.mobile_no as driver2_mobile,create_user.true_name as create_user,update_user.true_name as update_user,
				tti1.type_name as truck_type,tti1.id as truck_type_id,truck_appointment.*';
				$criteria->addCondition('truck_appointment.id='.($id!==null ? $id : $_GET['id']));
				$this->_model=Truck_appointment::model()->find($criteria);
			}
		return $this->_model;
	}

	public function loadGoods_info($id=null)
	{		
		if($id!==null || isset($_GET['id']))
			$criteria=new CDbCriteria();//INNER JOIN goods_name ON goods_name.id=goods_info.fk_goods_name_id
			$criteria->join='INNER JOIN path ON path.id=goods_info.fk_path_id
							 INNER JOIN consignor_info as consignor ON consignor.id=goods_info.fk_consignor_id
							 INNER JOIN consignee_info as consignee ON consignee.id=goods_info.fk_consignee_id';
			$criteria->select='consignor.name as consignor_name,consignee.name as consignee_name,
			path.loading_place as origin,path.pod_place as destination,
			path.mileage as path_mileage,goods_info.*';
			$criteria->addCondition('goods_info.fk_appointment_id='.($id!==null ? $id : $_GET['id']));
			$criteria->addCondition('goods_info.state=0');
			$models=Goods_info::model()->findAll($criteria);
		return $models;
	}
	
	public function loadDeadhead_info($id=null)
	{		
		if($id!==null || isset($_GET['id']))
			$models=Deadhead_info::model()->findAllByAttributes(array('fk_appointment_id'=>($id!==null ? $id : $_GET['id']),'state'=>0));
		return $models;
	}
	
	public function actionCheckTruckFuel(){
		if(Yii::app()->request->isAjaxRequest){
			if(isset($_POST['truck_id'])){
				$time=$_POST['time']==''?date('Y-m').'-01':$_POST['time'].'-01';
				$b=Fuel_consumption::model()->exists(array('condition'=>'fk_truck_id=:truck_id and state=0'." and '$time' BETWEEN  effect_date and lapse_date",
											'params'=>array(':truck_id'=>$_POST['truck_id'])));
				echo $b?1:0;
			}			
		}
	}
	
	public function actionCheckTruckMerit(){
		if(Yii::app()->request->isAjaxRequest){
			if(isset($_POST['truck_id'])){
				$time=$_POST['time']==''?date('Y-m').'-01':$_POST['time'].'-01';
				$b=Merit_pay_ratio::model()->exists(array('condition'=>'fk_truck_id=:truck_id and state=0'." and '$time' BETWEEN  effect_date and lapse_date",
											'params'=>array(':truck_id'=>$_POST['truck_id'])));
				echo $b?1:0;
			}			
		}
	}
	
	private function scheduleToGoods($sid,$g_model){
		$criteria=new CDbCriteria();
		$criteria->join='INNER JOIN path ON path.id=schedule_list.fk_path_id
						 INNER JOIN consignor_info as consignor ON consignor.id=schedule_list.fk_consignor_id
						 INNER JOIN goods_name ON goods_name.id=schedule_list.fk_goods_name_id';
		$criteria->select='consignor.name as consignor_name,path.loading_place as deliver_place,path.pod_place as arrival_place,
		path.mileage as mileage,goods_name.name as goods_name,schedule_list.*';
		$criteria->addCondition('schedule_list.id='.$sid);
		$s_model=Schedule_list::model()->find($criteria);
				
		$g_model->consignor_name=$s_model->consignor_name;
		$g_model->fk_consignor_id=$s_model->fk_consignor_id;
		$g_model->origin=$s_model->deliver_place;
		$g_model->destination=$s_model->arrival_place;
		$g_model->path_mileage=$s_model->mileage;
		$g_model->fk_path_id=$s_model->fk_path_id;
		$g_model->demand_deliver_time=$s_model->deliver_time;
		$g_model->demand_arrival_time=$s_model->arrival_time;
		$g_model->goods_name=$s_model->goods_name;
		//$g_model->fk_goods_name_id=$s_model->fk_goods_name_id;
		$g_model->unit_name=$s_model->unit_name;
		return $s_model;
	}
}
